<template>
  <div class="look-view">
    <a-row type="flex" style="width: 100%">
      <a-col :span="4" style="height: 100%;border-right: 1px solid #f1f1f1">
        <div class="group-box">
          <div class="group-list">
            <a-list
              :data-source="groupList"
              :split="false"
              :loading="groupLoading"
              class="view-list-one"
            >
              <template #header>
                <div class="group-title">
                  <div>分组管理</div>
                  <a-tooltip title="添加分组" @click.stop="handleAdd('group')">
                    <a-button type="link" style="margin-right: 0; padding-left: 4px; padding-right: 4px"><PlusCircleOutlined/></a-button>
                  </a-tooltip>
                </div>
              </template>
              <template #renderItem="{ item }">
                <a-list-item class="group-item" :class="item.id == currentGroupId ? 'active' : ''" @click.stop="changeCurrentGroup(item.id)">
                  {{item.name}}
                </a-list-item>
              </template>
            </a-list>
          </div>
        </div>
      </a-col>
      <a-col :span="20" style="height: 100%">
        <div class="tag-box">
          <a-alert type="warning">
            <template #description>
              <p>1、标签分组名称不能重复</p>
            </template>
          </a-alert>

          <a-table
            :dataSource="dataList"
            :columns="columns"
            :loading="loading"
            rowKey="id"
            :pagination="pagination"
            @change="handleTableChange"
            :row-selection="rowSelection"
          >
            <template #title>
              <a-row
                type="flex"
                justify="end"
                align="middle"
              >
                <a-col>
                  <a-space>
                    <a-button type="primary" ghost @click.stop="handleMove('tag')"
                    >移动标签</a-button>
                    <a-button type="primary" @click.stop="handleAdd('tag')"
                    >+新增标签</a-button>
                  </a-space>
                </a-col>
              </a-row>
            </template>

            <template #bodyCell="{ text, record, index, column }">
              <template v-if="column.key == 'customer_num'">
                <a-button type="link" @click="showCustomerList(record.id)">{{
                    record.customer_num
                  }}</a-button>
              </template>
              <template v-if="column.key === 'action'">
                <a-button type="link" @click.stop="handleEdit(record)">
                  编辑
                </a-button>
                <a-button type="link" danger @click.stop="handleDelete(record)">删除</a-button>
              </template>
            </template>
          </a-table>

        </div>
      </a-col>
    </a-row>


    <!-- 添加/编辑分组标签  -->
    <EditTags
      :visible="editVisible"
      :editType="editType"
      :id="editId"
      :editInfo="editInfo"
      :currentGroupId="currentGroupId"
      @handleCancel="handleCancel"
      @success="handleEditSuccess"
    />

    <!-- 移动标签  -->
    <MoveTags
      :visible="moveVisible"
      :currentGroupId="currentGroupId"
      :tagIds="selectedRowKeys"
      @handleCancel="moveVisible = false"
      @success="handleEditSuccess"
    />

    <!-- 客户列表 -->
    <CheckUserDetail
      :visible="showCustomer"
      :tagId="tagId"
      sourceType="tag"
      @closeDetail="closeDetail"
    />

  </div>
</template>

<script>
import {reactive, ref, toRefs, computed, watch, defineComponent, createVNode} from "vue";
import request from "@/common/utils/request";
import store from "@/store";
import {ExclamationCircleOutlined, PlusCircleOutlined} from "@ant-design/icons-vue";
import EditTags from "@/views/village/BusinessManage/tagModules/EditTags.vue";
import _ from "lodash";
import {message, Modal, notification} from "ant-design-vue";
import AddCustomerStatus from "@/views/village/BusinessManage/modules/AddCustomerStatus.vue";
import MoveTags from "@/views/village/BusinessManage/tagModules/MoveTags.vue";
import CheckUserDetail from "@/views/village/BusinessManage/modules/CheckUserDetail.vue";

export default defineComponent( {
  name: "tagManagementIndex",
  props: {
    activeKey: {
      type: [Number, String],
      default: '',
    },
  },
  components: {
    CheckUserDetail,
    AddCustomerStatus,
    PlusCircleOutlined,
    EditTags,
    MoveTags,
  },
  setup(props, { emit }) {
    const state = reactive({
      groupList: [],
      groupLoading: false,
      dataList: [],
      columns: COLUMNS,
      loading: false,
      page: 1,
      limit: 10,
      total: 0,
      editType: '',
      editVisible: false,
      editId: 0,
      currentGroupId: 0,
      editInfo: {},
      selectedRowKeys: [],
      moveVisible: false,
      showCustomer: false,
      tagId: 0,
    });
    const rowSelection = computed(() =>{
      return {
        selectedRowKeys: state.selectedRowKeys,
        onChange: onSelectedRowChange,
      }
    });


    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.limit,
      showSizeChanger: true,
    }));


    const onSelectedRowChange = (keys) => {
      state.selectedRowKeys = keys;
    };


    const getDataList = (init = false) => {
      state.loading = true;
      if (init) {
        state.page = 1;
        state.selectedRowKeys = [];
      }
      const params = {
        page: state.page,
        pageSize: state.limit,
        pid: state.currentGroupId,
      };

      request
        .get("/org", "/business/customerTag", params)
        .then((res) => {
          state.dataList = res?.list || [];
          state.total = res?.total || 0;
        })
        .finally(() => {
          state.loading = false;
        });
    };


    const handleTableChange = (pager) => {
      state.page = pager.current;
      state.limit = pager.pageSize;
      getDataList();
    };


    const handleAdd = (type) => {
      state.editType = type;
      state.editVisible = true;
    };

    const handleMove = () => {
      if (!state.selectedRowKeys?.length) {
        message.warning("请先选择要移动的标签");
        return
      }
      state.moveVisible = true;
    };

    const getGroupList = () => {
      state.groupLoading = true;
      return new Promise((resolve) => {
        request
          .get("/org", "/business/customerGroupTag", {})
          .then((res) => {
            state.groupList = res?.list || [];
            state.currentGroupId = res?.list[0]?.id || 0;
            resolve();
          })
          .finally(() => {
            state.groupLoading = false;
          });
      });
    };

    const handleCancel = () => {
      state.editVisible = false;
      state.editId = 0;
      state.editInfo = {};
      state.moveVisible = false;
    };
    const handleEditSuccess = (type) => {
      handleCancel();
      state.selectedRowKeys = [];
      if (type == 'group') {
        init();
      } else {
        getDataList();
      }
    };

    const changeCurrentGroup = (id) => {
      state.currentGroupId = id;
      getDataList(true);
    };

    const handleEdit = (record) => {
      state.editVisible = true;
      state.editType = 'tag';
      state.editId = record.id;
      state.editInfo = _.cloneDeep(record);
    };

    const handleDelete = (record) => {
      Modal.confirm({
        title: () => "提示",
        content: () => "确定要删除该标签吗？",
        icon: () => createVNode(ExclamationCircleOutlined),
        okText: () => "确定",
        onOk() {
          request
            .del("/org", "/business/customerTag", {id: record.id})
            .then((res) => {
              message.success(res?.msg || '删除成功');
              state.selectedRowKeys = [];
              getDataList();
            })
        },
      });
    };

    const closeDetail = () => {
      state.tagId = 0;
      state.showCustomer = false;
    };

    const showCustomerList = (val) => {
      state.tagId = val;
      state.showCustomer = true;
    };


    const init = () => {
      getGroupList().then(() => {
        getDataList(true);
      })
    };


    watch(
      () => props.activeKey,
      (val) => {
        if (val) {
          if (val == 1) {
            init();
          }
        }
      },
      { immediate: true }
    );

    return {
      ...toRefs(state),
      pagination,
      rowSelection,
      handleTableChange,
      handleAdd,
      handleEditSuccess,
      changeCurrentGroup,
      handleCancel,
      handleEdit,
      handleDelete,
      handleMove,
      showCustomerList,
      closeDetail,
    };
  },
});

const COLUMNS = [
  {
    title: "标签名称",
    align: "center",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "意向客户数",
    align: "center",
    dataIndex: "customer_num",
    key: "customer_num",
  },
  {
    title: "操作",
    align: "center",
    dataIndex: "id",
    key: "action",
    width: 180,
    fixed: "right",
  },

]
</script>

<style lang="less" scoped>
.look-view {
  height: 100%;
  display: flex;
  padding: 14px 0;
  p {
    &:last-of-type {
      margin-bottom: 0;
    }
  }
}
.group-box {
  width: 100%;
  height: 100%;
  padding: 0 14px;
  display: flex;
  flex-direction: column;
  .group-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 15px;
    font-weight: bold;
  }
}
.view-list-one {
  flex: 1;
  width: 0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}
.group-list {
  flex: 1;
  display: flex;
  overflow: hidden;
}
.look-box {
  height: 100%;
}
.tag-box {
  width: 100%;
  height: 100%;
  padding: 0 14px;
  overflow-y: auto;
}
.group-item {
  border-bottom: 1px dashed #d9d9d9;
  cursor: pointer;
  &:hover {
    color: @primary-color;
  }
}
.active {
  color: @primary-color;
}
</style>
